package pub.guoxin.oops.manager.service.impl;

import com.querydsl.core.types.dsl.BooleanExpression;
import org.assertj.core.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import pub.guoxin.oops.enums.Authority;
import pub.guoxin.oops.manager.service.AlarmDisposeService;
import pub.guoxin.oops.manager.vo.AlarmDisposeVo;
import pub.guoxin.oops.model.AlarmDispose;
import pub.guoxin.oops.model.Group;
import pub.guoxin.oops.model.QAlarmDispose;
import pub.guoxin.oops.model.User;
import pub.guoxin.oops.repository.AlarmDisposeRepository;
import pub.guoxin.oops.repository.GroupRepository;

import java.util.Objects;

/**
 * Create by guoxin on 2018/5/5
 */
@Service
public class AlarmDisposeServiceImpl implements AlarmDisposeService {

    @Autowired
    private AlarmDisposeRepository alarmDisposeRepository;
    @Autowired
    private GroupRepository groupRepository;

    @Override
    public Page<AlarmDisposeVo> page(User user, String groupId, String deviceSn, String fieldName, Integer pageNumber, Integer pageSize) {
        QAlarmDispose qAlarmDispose = QAlarmDispose.alarmDispose;
        Group group = groupRepository.findByUserId(user.getId());
        if (Objects.isNull(group)) {
            return null;
        }
        BooleanExpression eq;
        if (Authority.ROLE_ADMIN.equals(user.findFirstAuthorityEnum())) {
            eq = qAlarmDispose.companyId.eq(user.getCompanyId());
        } else if (Authority.ROLE_ADMIN.equals(user.findFirstAuthorityEnum())) {
            eq = qAlarmDispose.groupId.eq(group.getId());
        } else {
            return null;
        }
        if (!Strings.isNullOrEmpty(groupId)) {
            eq = qAlarmDispose.groupId.like(groupId);
        }
        if (!Strings.isNullOrEmpty(deviceSn)) {
            eq = qAlarmDispose.deviceSn.eq(deviceSn);
        }
        if (!Strings.isNullOrEmpty(fieldName)) {
            eq = qAlarmDispose.fieldName.eq(fieldName);
        }
        Pageable request = new PageRequest(pageNumber - 1, pageSize, Sort.Direction.DESC, "creation");
        Page<AlarmDispose> all = alarmDisposeRepository.findAll(eq, request);
        return all.map(alarmDispose -> {
            Group one = groupRepository.findOne(alarmDispose.getCompanyId());
            return new AlarmDisposeVo(alarmDispose, one.getName());
        });
    }

    @Override
    public boolean remark(User user, String id, String remark) {
        AlarmDispose one = alarmDisposeRepository.findOne(id);
        if (Objects.isNull(one)) {
            return false;
        }
        one.setRemark(remark);
        alarmDisposeRepository.save(one);
        return true;
    }
}
